package com.example.demo.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.bean.Entity;
import com.example.demo.utils.JwtHelper;

@CrossOrigin(allowCredentials = "true", origins = "*", maxAge = 3600, methods = { RequestMethod.GET, RequestMethod.POST,
		RequestMethod.PUT,
		RequestMethod.OPTIONS }, allowedHeaders = { "x-requested-with", "accept", "authorization", "content-type" })
@Controller
public class FileController {
	protected final Logger logger = LogManager.getLogger(this.getClass());

	@Autowired
	private Entity entity;
	
	@Value("${img.path}")
	String pathName;
	
	@RequestMapping("/file")
	public Object file (HttpServletRequest request, HttpServletResponse response) {
		return "pic.html";
	}
	@RequestMapping("/file2")
	public Object file2 (HttpServletRequest request, HttpServletResponse response) {
		return "picc.html";
	}
	
	@RequestMapping("/uploadPage")
    public String uploadPage() {
        return "uploadPage";   //过度跳转页
    }

	@RequestMapping("/upload2") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uplaod2(@RequestParam("file") MultipartFile file,HttpServletRequest req,  Model m) {//1. 接受上传的文件  @RequestParam("file") MultipartFile file
        try {
            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
        	 String fileName = System.currentTimeMillis() +"_"+ file.getOriginalFilename();
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
            System.out.println(req.getServletContext().getRealPath(""));	
//            String destFileName = "f:/" + "uploaded" + File.separator + fileName;
            String destFileName = pathName + fileName;
            System.out.println(destFileName);
            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);
            //6.把文件名放在model里，以便后续显示用
            m.addAttribute("pic_name", fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
//    	    return new HashMap<String,Object>(){{put("code",200);put("msg","上传失败");put("status", false);}};
        } catch (IOException e) {
            e.printStackTrace();
//    	    return new HashMap<String,Object>(){{put("code",200);put("msg","上传失败");put("status", false);}};
        }
//	    return new HashMap<String,Object>(){{put("code",200);put("msg","success");put("status", true);}};
        return "show.html";
    }
	
	@RequestMapping("/upload") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
    public Map<String,Object> uplaod(@RequestParam("file") MultipartFile file,HttpServletRequest req,  Model m,HttpServletResponse response) {//1. 接受上传的文件  @RequestParam("file") MultipartFile file
		String token = JwtHelper.token();
		System.out.println(token);
		response.setHeader("token", token);
		//2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
		String fileName = System.currentTimeMillis() + file.getOriginalFilename();
		try {
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
//            System.out.println(req.getServletContext().getRealPath(""));	
//            String destFileName = "f:/" + "uploaded" + File.separator + fileName;
            String destFileName = pathName + fileName;
            System.out.println(destFileName);
            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);
            //6.把文件名放在model里，以便后续显示用
            m.addAttribute("fileName", fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
    	    return new HashMap<String,Object>(){{put("code",200);put("msg","上传失败");put("status", false);}};
        } catch (IOException e) {
            e.printStackTrace();
    	    return new HashMap<String,Object>(){{put("code",200);put("msg","上传失败");put("status", false);}};
        }
	    return new HashMap<String,Object>(){{put("code",200);put("msg","success");put("status", true);put("pic_name",fileName);}};
    }
	
	@RequestMapping("/show") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView show(HttpServletRequest req,String pic_name) {
//		model.addAttribute("pic_name", namename);
		ModelAndView mv = new ModelAndView();
		mv.setViewName("show.html");
		mv.addObject("pic_name", pic_name);
		return mv;
	}
}
